package com.dreamlin.demo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.SSLCertificateSocketFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;

import com.dreamlin.lindownload.LinDownload;
import com.dreamlin.lindownload.LinDownloadListener;
import com.dreamlin.lindownload.entity.LinTaskBean;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.zip.Inflater;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;

import io.realm.Realm;

public class MainActivity extends AppCompatActivity {

    private List<TaskBean> taskList;
    private Adapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RecyclerView rvList = findViewById(R.id.rv_list);
        taskList = new ArrayList<>();
        adapter = new Adapter(taskList);
        rvList.setLayoutManager(new LinearLayoutManager(this));
        rvList.setAdapter(adapter);
        Executors.newSingleThreadExecutor().execute(() -> {
            File file = new File(getExternalCacheDir().getPath(), "测试图片.jpg");
            long length = file.length();
            System.out.println(length);
            try {
                FileInputStream fis = new FileInputStream(file);
                Bitmap bitmap = BitmapFactory.decodeStream(fis);
                runOnUiThread(() -> {
                    taskList.get(0).setBitmap(bitmap);
                    adapter.notifyItemChanged(0);
                });
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        });
        init();
    }

    private void init() {
        LinDownload.init(this);
        //https://ugc-download-2.imfir.cn/dc6e5151fd49d762a908ba1b40e855fd27e60742.apk?auth_key=1589357569-0-0-7e53942a4a0aa44326bd7c2333557ff0
        TaskBean taskBean = new TaskBean("http://192.168.4.28:8082/static/image/app-release.apk");
        taskBean.setCallInterval(1000L);
        taskBean.setSavePath(Objects.requireNonNull(getExternalCacheDir()).getPath());
        taskBean.setThreadNum(6);
        taskList.add(taskBean);
        TaskBean clone1 = taskBean.clone();
        TaskBean clone2 = taskBean.clone();
        TaskBean clone3 = taskBean.clone();
        TaskBean clone4 = taskBean.clone();
        TaskBean clone5 = taskBean.clone();
        TaskBean clone6 = taskBean.clone();
        clone1.setUrl("http://192.168.4.28:8082/static/image/app-release2.apk");
        clone2.setUrl("http://192.168.4.28:8082/static/image/app-release3.apk");
        clone3.setUrl("http://192.168.4.28:8082/static/image/app-release4.apk");
        clone4.setUrl("http://192.168.4.28:8082/static/image/app-release5.apk");
        clone5.setUrl("http://192.168.4.28:8082/static/image/app-release6.apk");
        clone6.setUrl("http://192.168.4.28:8082/static/image/app-release7.apk");
        taskList.add(clone1);
        taskList.add(clone2);
        taskList.add(clone3);
        taskList.add(clone4);
        taskList.add(clone5);
        taskList.add(clone6);
        adapter.notifyDataSetChanged();
    }

    static class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {

        List<TaskBean> taskBeans;

        public Adapter(List<TaskBean> taskBeans) {
            this.taskBeans = taskBeans;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View inflate = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.item_task, parent, false
            );
            return new ViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            holder.bindItem(taskBeans.get(position), position);
        }

        @Override
        public int getItemCount() {
            return taskBeans == null ? 0 : taskBeans.size();
        }


        class ViewHolder extends RecyclerView.ViewHolder {

            private TextView tvName;
            private TextView tvSpeed;
            private SeekBar seekBar;
            private Button btnController;
            private Button btnCancel;
            private AppCompatImageView ivDownload;
            private TaskBean linTaskBean;
            private int position;

            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                tvName = itemView.findViewById(R.id.tv_name);
                tvSpeed = itemView.findViewById(R.id.tv_speed);
                seekBar = itemView.findViewById(R.id.seek_bar);
                btnController = itemView.findViewById(R.id.btn_controller);
                btnCancel = itemView.findViewById(R.id.btn_cancel);
                ivDownload = itemView.findViewById(R.id.iv_download);
                btnController.setOnClickListener(v -> {
                    if (LinDownload.isDownloading(linTaskBean.getUrl())) {
                        LinDownload.with(linTaskBean.getUrl()).pause();
                        btnController.setText("开始");
                    } else {
                        LinDownload.with(linTaskBean.getUrl())
                                .name(linTaskBean.getFileName())
                                .path(linTaskBean.getSavePath())
                                .threadNum(linTaskBean.getThreadNum())
                                .callInterval(1000L)
                                .listener(new DownloadListener())
                                .start();
                        btnController.setText("暂停");
                    }
                });
                btnCancel.setOnClickListener(v -> {
                    LinDownload.with(linTaskBean.getUrl())
                            .cancel();
                });
            }

            public void bindItem(TaskBean linTaskBean, int position) {
                this.linTaskBean = linTaskBean;
                this.position = position;
                tvName.setText(linTaskBean.getFileName());
                if (linTaskBean.getBitmap() != null) {
                    ivDownload.setImageBitmap(linTaskBean.getBitmap());
                }
            }

            class DownloadListener implements LinDownloadListener {
                @Override
                public void onTaskWait(LinTaskBean linTaskBean) {

                }

                @Override
                public void onTaskStart(LinTaskBean linTaskBean) {
                    btnController.setText("暂停");
                }

                @Override
                public void onTaskProgress(LinTaskBean linTaskBean, long finished, long total, String speed) {
                    int percent = (int) ((float) finished / (float) total * 100);
                    seekBar.setProgress(percent);
                    tvSpeed.setText(speed);
                }

                @Override
                public void onTaskSuccess(LinTaskBean linTaskBean) {
                    seekBar.setProgress(100);
                    taskBeans.get(position).setFinish(true);
                    btnCancel.setText("删除");
                    btnController.setText("安装");
                }

                @Override
                public void onTaskFailed(LinTaskBean linTaskBean) {

                }

                @Override
                public void onTaskPause(LinTaskBean linTaskBean) {
                    btnController.setText("开始");
                }

                @Override
                public void onTaskCancel(LinTaskBean linTaskBean) {
                    taskBeans.remove(position);
                }

                @Override
                public void onTaskRetry(LinTaskBean linTaskBean) {

                }
            }
        }
    }

}
